import { useAppSelector } from '@/store';
import {
  addUserChannelByIdAction,
  delUserChannelByIdAction,
  getChannelListAction,
  getUserChannelListAction,
  setChannelIdAction,
} from '@/store/action/channel';
import { Popup, Tabs, Toast } from 'antd-mobile';
import React, { useEffect, useState } from 'react';
import { useDispatch } from 'react-redux';
import Icon from '../Icon';
import styles from './index.module.scss';
import { differenceBy } from 'lodash';
import { ChannelType } from '@/store/reducer/channel';
import { getLocalChannels, hasToekn, setLocalChannels } from '@/utils/storage';
import { useHistory } from 'react-router-dom';

export default function Channel() {
  const dispatch = useDispatch();
  useEffect(() => {
    dispatch(getChannelListAction());
    dispatch(getUserChannelListAction());
  }, [dispatch]);

  const history = useHistory();

  const { userList, allList, currentId } = useAppSelector((state) => state.channel);
  const [visible, setVisible] = useState(false);

  const restList = differenceBy(allList, userList, 'id');
  const [editable, setEditable] = useState(false);

  const handleDelById = async (id: number) => {
    if (id === 0) {
      return Toast.show({ content: '不允许删除推荐频道' });
    }
    if (!hasToekn()) {
      let list = getLocalChannels();
      if (list.length === 5) {
        return Toast.show({ content: '至少保留5个' });
      }
      list = list.filter((item) => {
        return item.id !== id;
      });
      setLocalChannels(list);
      dispatch({ type: 'channel/delUserChannelById', payload: id });
      Toast.show({ content: '删除成功' });
      return;
    }

    if (userList.length === 5) {
      return Toast.show({ content: '至少保留5个' });
    }
    await dispatch(delUserChannelByIdAction(id));
    Toast.show({ content: '删除成功' });
  };

  const handleAddChannel = async (newChannel: ChannelType) => {
    if (!hasToekn()) {
      setLocalChannels([...getLocalChannels(), newChannel]);
      dispatch({
        type: 'channel/addUserChannel',
        payload: newChannel,
      });
      Toast.show({ content: '设置成功' });
      return;
    }
    await dispatch(addUserChannelByIdAction(newChannel));
    Toast.show({ content: '设置成功' });
  };

  const handleUpdateChannelId = (id: string) => {
    dispatch(setChannelIdAction(Number(id)));
  };
  return (
    <div className={styles.root}>
      <Tabs activeKey={String(currentId)} className="tabs" onChange={handleUpdateChannelId}>
        {userList.map((item) => {
          return <Tabs.Tab title={item.name} key={item.id}></Tabs.Tab>;
        })}
      </Tabs>
      <div className="right">
        {/* 2. */}
        <Icon type="iconbtn_search" onClick={() => history.push('/search')} />
        <Icon type="iconbtn_channel" onClick={() => setVisible(true)} />
      </div>
      <Popup visible={visible} position="left" bodyClassName={styles.channelPopup}>
        <div className="channel-header">
          <Icon
            type="iconbtn_channel_close"
            onClick={() => {
              setVisible(false);
              setEditable(false);
            }}
          />
        </div>

        <div className="channel-content">
          <div className="channel-item edit">
            <div className="channel-item-header">
              <span className="channel-item-title">我的频道</span>
              <span className="channel-item-title-extra">点击删除频道</span>
              <span className="channel-item-edit" onClick={() => setEditable(!editable)}>
                {editable ? '完成' : '编辑'}
              </span>
            </div>

            <div className="channel-list">
              {userList.map((item) => {
                return (
                  <span className="channel-list-item" key={item.id}>
                    {item.name}
                    {editable && (
                      <Icon type="iconbtn_tag_close" onClick={() => handleDelById(item.id)} />
                    )}
                  </span>
                );
              })}
            </div>
          </div>

          <div className="channel-item">
            <div className="channel-item-header">
              <span className="channel-item-title">频道推荐</span>
              <span className="channel-item-title-extra">点击添加频道</span>
            </div>
            <div className="channel-list">
              {restList.map((item) => {
                return (
                  <span
                    key={item.id}
                    className="channel-list-item"
                    onClick={() => handleAddChannel(item)}
                  >
                    + {item.name}
                  </span>
                );
              })}
            </div>
          </div>
        </div>
      </Popup>
    </div>
  );
}
